<style lang="less">
    @import "./newsManage.less";
</style>
<template>
    <div class="search">
        <Row>
            <Col>
            <Card>
                <p slot="title">
                    <span v-if="type==0">发送新消息</span>
                    <span v-else>编辑消息</span>
                </p>
                <Row>
                    <Form ref="form" :model="form" :label-width="70" :rules="formValidate" style="position:relative">
                        <FormItem label="标题" prop="messageTitle">
                            <Input v-model="form.messageTitle" style="width:600px"/>
                        </FormItem>
                        <FormItem label="排序" prop="sortOrder">
                            <Input type="number" v-model="form.sortOrder" style="width:600px"/>
                        </FormItem>
                        <FormItem label="摘要" prop="summary" >
                            <Input v-model="form.summary" type="textarea" autocomplete="off"/>
                        </FormItem>
                        <FormItem label="内容" prop="messageContent">
                            <div ref="editor"></div>
                        </FormItem>
                        <Form-item label class="br">
                            <Button @click="editHTML" icon="ios-create-outline">编辑HTML代码</Button>
                            <Button @click="fullscreenModal=true" icon="md-eye">预览</Button>
                        </Form-item>
                        <FormItem label="封面图" prop="newsImg">
                            <upload-input :fileUrl="form.newsImg" :fileSize="fileSize" fileWh="750*566" @on-change="handleUpload" width="400px" ref="upload"></upload-input>
                        </FormItem>
                        <Form-item class="br">
                            <Button type="primary" :loading="submitLoading" @click="handelSubmit" style="width:100px">提交</Button>
                            <Button @click="handelCancel">取消</Button>
                        </Form-item>
                        <Spin size="large" fix v-if="loading"></Spin>
                    </Form>
                </Row>
            </Card>
            </Col>
        </Row>
        <!-- html编辑 -->
        <Modal title="编辑html代码" v-model="showHTMLModal" :mask-closable="false" :width="900" :fullscreen="full">
            <Input v-if="!full" v-model="dataEdit" :autosize="true" type="textarea" style="max-height:60vh;overflow:auto"/>
            <Input v-if="full" v-model="dataEdit" :autosize="true" type="textarea"/>
            <div slot="footer">
                <Button @click="full=!full" icon="md-expand">全屏开/关</Button>
                <Button @click="editHTMLOk" type="primary" icon="md-checkmark-circle-outline">确定保存</Button>
            </div>
        </Modal>
        <Modal title="预览" v-model="fullscreenModal" fullscreen>
            <div v-html="form.messageContent">{{form.messageContent}}</div>
            <div slot="footer">
                <Button @click="fullscreenModal=false">关闭</Button>
            </div>
        </Modal>
    </div>
</template>

<script>
    import {addNews, editMessage, getMessageDataById, uploadFile} from "@/api/index";
    import E from "wangeditor";
    // 表情包配置 自定义表情可在该js文件中统一修改
    import {sina} from "@/libs/emoji";
    import uploadInput from "@/views/my-components/flyme/upload-input";

    let editor = null;
    export default {
        name: "add_edit_news",
        components: {
            uploadInput
        },
        data() {
            return {
                type: 0,
                loading: false, // 表单加载状态
                selectUsers: [],
                userModalVisible: false,
                modalTitle: "", // 添加或编辑标题
                form: {
                    // 添加或编辑表单对象初始化数据
                    messageTitle: "",
                    messageContent: "",
                    messageType: 0,
                    range: 0,
                    sortOrder: 0,
                    newsImg: "",
                    summary: ""
                },
                formValidate: {
                    // 表单验证规则
                    messageTitle: [{required: true, message: "标题不能为空", trigger: "blur"}],
                    messageContent: [{required: true, message: "内容不能为空", trigger: "blur"}]
                },
                submitLoading: false, // 添加或编辑提交状态
                dictMessageType: [],
                dictSex: [],
                dataEdit: "", // 编辑数据
                showHTMLModal: false, // 显示html
                full: false, // html全屏开关
                fullscreenModal: false, // 显示全屏预览
                backRoute: ""
            };
        },
        methods: {
            init() {
                this.initEditor();
                this.type = this.$route.query.type;
                this.backRoute = this.$route.query.backRoute;
                if (this.type == 1) {
                    this.form.id = this.$route.query.id;
                    this.getData();
                }
            },
            initEditor() {
                let that = this;
                editor = new E(this.$refs.editor);
                editor.customConfig.onchange = html => {
                    this.form.messageContent = html;
                };
                editor.customConfig.uploadImgServer = uploadFile;
                editor.customConfig.uploadImgHeaders = {
                    Authorization: that.getStore("accessToken")
                };
                editor.customConfig.uploadFileName = "file";
                editor.customConfig.uploadImgHooks = {
                    before: function (xhr, editor, files) {
                    },
                    success: function (xhr, editor, result) {
                    },
                    fail: function (xhr, editor, result) {
                        that.$Message.error("上传图片失败");
                    },
                    error: function (xhr, editor) {
                        that.$Message.error("上传图片出错");
                    },
                    timeout: function (xhr, editor) {
                        that.$Message.error("上传图片超时");
                    },
                    customInsert: function (insertImg, result, editor) {
                        if (result.status === true) {
                            let url = result.data.fileUrl;
                            insertImg(url);
                            that.$Message.success("上传图片成功");
                        } else {
                            that.$Message.error(result.info);
                        }
                    }
                };
                editor.customConfig.fontNames = ["微软雅黑", "宋体", "黑体", "Arial"];
                editor.customConfig.emotions = [
                    {
                        title: "新浪",
                        type: "image",
                        content: sina
                    }
                ];
                editor.create();
            },
            editHTML() {
                this.dataEdit = this.form.messageContent;
                this.showHTMLModal = true;
            },
            handleUpload(v) {
                if (v) {
                    this.form.newsImg = v.fileUrl;
                }
            },
            editHTMLOk() {
                editor.txt.html(this.dataEdit);
                this.form.messageContent = this.dataEdit;
                this.showHTMLModal = false;
            },
            getData() {
                this.loading = true;
                getMessageDataById(this.form.id).then(res => {
                    this.loading = false;
                    if (res.status === true) {
                        // 转换null为""
                        let v = res.data;
                        for (let attr in v) {
                            if (v[attr] === null) {
                                v[attr] = "";
                            }
                        }
                        let str = JSON.stringify(v);
                        let data = JSON.parse(str);
                        editor.txt.html(data.messageContent);
                        this.form = data;
                    }
                });
            },
            handelSubmit() {
                this.$refs.form.validate(valid => {
                    if (valid) {
                        this.submitLoading = true;

                        if (this.type == 0) {
                            // 添加 避免编辑后传入id等数据 记得删除
                            delete this.form.id;
                            // 用户id数据
                            let ids = [];
                            this.selectUsers.forEach(e => {
                                ids.push(e.id);
                            });
                            this.form.userIds = ids;
                            addNews(this.form).then(res => {
                                this.submitLoading = false;
                                if (res.status === true) {
                                    this.$Message.success("操作成功");
                                    this.closeCurrentPage();
                                }
                            });
                        } else if (this.type == 1) {
                            // 编辑
                            editMessage(this.form).then(res => {
                                this.submitLoading = false;
                                if (res.status === true) {
                                    this.$Message.success("操作成功");
                                    this.closeCurrentPage();
                                }
                            });
                        }
                    }
                });
            },
            handleSelectUser(v) {
                this.selectUsers = v;
            },
            handelCancel() {
                this.closeCurrentPage();
            },
            // 关闭当前页面
            closeCurrentPage() {
                this.$store.commit("removeTag", "add_edit_news");
                localStorage.pageOpenedList = JSON.stringify(
                    this.$store.state.app.pageOpenedList
                );
                this.$router.push({
                    name: this.backRoute
                });
            }
        },
        mounted() {
            this.init();
        },
        watch: {
            // 监听路由变化
            $route(to, from) {
                if (to.name == "add_edit_news") {
                    this.type = this.$route.query.type;
                    if (this.type == 1) {
                        this.form.id = this.$route.query.id;
                        this.getData();
                    }else{
                        editor.txt.html("");
                    }
                }
            }
        }
    };
</script>